package com.atguigu.tingshu.order.interceptor.impl;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Slf4j
@Service
public class OrderRepeatSbumitValidOrderHandlerInterceptor implements OrderHandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public OrderInfoVo sbumitOrderRequestProcess(OrderInfoVo orderInfoVo) {
        /**
         * 校验表单重复提交
         */
        //LUA脚本 如果存在，则删除，返回1，否则返回0
        String scrip = "if redis.call(\"exists\",KEYS[1])\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        //执行lua脚本
        Long execute = stringRedisTemplate.execute(new DefaultRedisScript<>(scrip, Long.class),
                Arrays.asList(RedisConstant.ORDER_TRADE_NO_PREFIX + orderInfoVo.getTradeNo()));
        //判断是否重复
        if (execute.intValue() == 0) {
            throw new GuiguException(ResultCodeEnum.REPEAT_SUBMIT);
        }
        log.info("表单重复提交校验完毕....");
        return orderInfoVo;
    }

    @Override
    public int sort() {
        return 2;
    }
}
